package cn.xiaomubiao.oschine.fragment.News_fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import cn.xiaomubiao.oschine.R;
import cn.xiaomubiao.oschine.base.BaseEachFragment;
import cn.xiaomubiao.oschine.bean.Blog;
import cn.xiaomubiao.oschine.bean.BlogDetail;
import cn.xiaomubiao.oschine.util.HttpUtil;
import cn.xiaomubiao.oschine.util.OnWebViewImageListener;
import cn.xiaomubiao.oschine.util.StringUtils;
import cn.xiaomubiao.oschine.util.ToastUtils;
import cn.xiaomubiao.oschine.util.UIHelper;
import cn.xiaomubiao.oschine.util.UIUtils;

/**
 * 资讯详情页面的Fragment 继承
 */

public class BlogsDetailFragment extends BaseEachFragment {

    private Activity activity = getActivity();
    private WebView mWebview;
//    private NewsDetail datas;
    private BlogDetail datas;

    // 加载成功时的界面
    @Override
    public View loadSuccess() {
        // 将布局文件进行打气
        View view = View.inflate(getContext(), R.layout.news_title_xiangqing, null);

        // 找到里面的webview控件
        mWebview = (WebView) view.findViewById(R.id.webview);

        // 加载数据到webview中
        executeOnLoadDataSuccess(datas);

        // 最后将视图对象返回
        return view;

    }

    @Override
    public void loadData() {
        // 获取在Activity替换当前的fragment时传递过来的数据 id 用于拼接
        Bundle arguments = getArguments();
        int pagerId = (int) arguments.get("id");

        // 拼接url
        String url = "http://10.0.2.2:8080/oschina/detail/blog_detail/" + pagerId + ".xml";

        // 进行网络数据请求
        HttpUtil<BlogDetail> http = new HttpUtil(activity, BlogDetail.class);
        http.getStringData(url, new HttpUtil.OnGetDataListener<BlogDetail>() {
            @Override
            public void onSuccess(final BlogDetail newsDetail) {
                datas = newsDetail;

                // 调用成功界面
                mCommonPager.showSuccessPager(datas);

            }

            @Override
            public void onFailure(Exception e) {
                ToastUtils.showToastLong(UIUtils.getContext(), "连接错误");

                mCommonPager.showFailPager();


            }
        });

    }


    //源码实现
    protected void executeOnLoadDataSuccess(BlogDetail newsDetail) {
        Blog news = newsDetail.getBlog();
        //处理网页内容,添加数据,为图片设置点击事件
        String webViewBody = this.getWebViewBody(news);//添加内容

        //设置监听
        addWebImageShow(activity, mWebview);//设置监听

        //开始加载
        mWebview.loadDataWithBaseURL("", webViewBody, "text/html", "UTF-8", "");
    }

    //动态添加,替换内容
    protected String getWebViewBody(Blog mDetail) {
        StringBuffer body = new StringBuffer();
        body.append(UIHelper.WEB_STYLE).append(UIHelper.WEB_LOAD_IMAGES);
        // 添加title
        body.append(String.format("<div class='title'>%s</div>", mDetail.getTitle()));
        // 添加作者和时间
        String time = StringUtils.friendly_time(mDetail.getPubDate());
        String author = String.format("<a class='author' href='http://my.oschina.net/u/%s'>%s</a>", mDetail.getAuthorId(), mDetail.getAuthor());
        body.append(String.format("<div class='authortime'>%s&nbsp;&nbsp;&nbsp;&nbsp;%s</div>", author, time));
        // 添加图片点击放大支持
        body.append(setHtmlCotentSupportImagePreview(mDetail.getBody()));


        // 更多关于***软件的信息
/*
        String softwareName = mDetail.getSoftwareName();
        String softwareLink = mDetail.getSoftwareLink();
        if (!StringUtils.isEmpty(softwareName)
                && !StringUtils.isEmpty(softwareLink))
            body.append(String
                    .format("<div class='oschina_software' style='margin-top:8px;font-weight:bold'>更多关于:&nbsp;<a href='%s'>%s</a>&nbsp;的详细信息</div>",
                            softwareLink, softwareName));
*/

/*        // 相关新闻
        if (mDetail != null && mDetail.getRelatives() != null
                && mDetail.getRelatives().size() > 0) {
            String strRelative = "";
            for (News.Relative relative : mDetail.getRelatives()) {
                strRelative += String.format(
                        "<li><a href='%s' style='text-decoration:none'>%s</a></li>",
                        relative.url, relative.title);
            }
            body.append("<p/><div style=\"height:1px;width:100%;background:#DADADA;margin-bottom:10px;\"/>"
                    + String.format("<br/> <b>相关资讯</b><ul class='about'>%s</ul>",
                    strRelative));
        }*/
        body.append("<br/>");
        // 封尾
        body.append("</div></body>");
        return body.toString();
    }

    //所有图片设置点击事件,调用java本地代码
    public static String setHtmlCotentSupportImagePreview(String body) {
        // 读取用户设置：是否加载文章图片--默认有wifi下始终加载图片
        if (true) {
            // 过滤掉 img标签的width,height属性
            body = body.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+", "$1");
            body = body.replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+", "$1");
            // 添加点击图片放大支持
            // 添加点击图片放大支持
            body = body.replaceAll("(<img[^>]+src=\")(\\S+)\"",
                    "$1$2\" onClick=\"javascript:mWebViewImageListener.showImagePreview('$2')\"");
        } else {
            // 过滤掉 img标签
            body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>", "");
        }
        return body;
    }

    //js中调用该方法后,启动新的页面展示图片
    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    @JavascriptInterface
    public static void addWebImageShow(final Context cxt, WebView wv) {
        wv.getSettings().setJavaScriptEnabled(true);
        wv.addJavascriptInterface(new OnWebViewImageListener() {
            @Override
            @JavascriptInterface
            public void showImagePreview(String bigImageUrl) {
                if (bigImageUrl != null && !StringUtils.isEmpty(bigImageUrl)) {
                    UIHelper.showImagePreview(cxt, new String[]{bigImageUrl});
                }
            }
        }, "mWebViewImageListener");
    }

}